var hpcJobInputFiles = [],
hpcJobSourceFiles = [];
var hpcLongDescription = [],
hpcVMDescription = [];

function hpcShowDescription() {
    //console.log(event.srcElement);
    //console.log(event.srcElement.value);
    var index = event.srcElement.value;
    //console.log(hpcLongDescription[index]);
    $("#craneModalDialogContent").text(hpcLongDescription[index]);
    $('#craneModalDialog').dialog({
        buttons: {
            OK: function() {
                $(this).dialog('close');
            }
        }
    }).dialog('open');
};

function hpcShowVMDescription() {
    //console.log(event.srcElement);
    //console.log(event.srcElement.value);
    var index = event.srcElement.value;
    //console.log(hpcLongDescription[index]);
    $("#craneModalDialogContent").text(hpcVMDescription[index]);
    $('#craneModalDialog').dialog({
        buttons: {
            OK: function() {
                $(this).dialog('close');
            }
        }
    }).dialog('open');
};
    
var user_HPC = function() {

    //construct create virtual cluster dialog
    $('#userHpcVirtualClusterCreationDialog').dialog({
        width: 450,
        height: 500,
        autoOpen: false,
        modal: false,
        title: 'Create Virtual Cluster'
    });
    /*
    function startList() {
        if (document.all && document.getElementById) {
            var navRoot = document.getElementById("nav");
            for (var i = 0; i < navRoot.childNodes.length; i++) {
                var node = navRoot.childNodes[i];
                if (node.nodeName == "LI") {
                    node.onmouseover = function() {
                        this.className += " over";
                    }
                    node.onmouseout = function() {
                        this.className = this.className.replace(" over", "");
                    }
                }
            }
        }
    };

    startList();
*/
    function userHPCLoadHPCTemplateTable() {
        $('#userHpcTemplateInfoTable').dataTable().fnClearTable();
        for (var j = 0; j < allsites.length; j += 1) { (function(siteName) {
                $.post('/' + siteName + '/hpc/execute_wait/mpiapi.show_mpi_image.json', {},
                function(serverResponse) {
                    //$('#loginActivityIndicator').hide(); 
                    var mem;
                    var shortdescription;
                    var storage;
                    var id;
                    var cpu;
                    for (var i = 0; i < serverResponse[0]; i += 1) {
                        mem = serverResponse[1][i].MEM;
                        shortdescription = serverResponse[1][i].SHORT;
                        hpcLongDescription[shortdescription] = serverResponse[1][i].LONG;
                        storage = serverResponse[1][i].STORAGE;
                        id = serverResponse[1][i].ID;
                        cpu = serverResponse[1][i].CPU;
                        if (shortdescription === '') {
                            shortdescription = 'No Description!';
                        }
                        $('#userHpcTemplateInfoTable').dataTable().fnAddData([
                        siteName, id, cpu, mem, storage, ' <input type="button" value="' + shortdescription + '" onclick="hpcShowDescription()" style="width:120px"  > </input>' ]);
                        //console.log(serverResponse);
                        //console.log(mem );
                        //console.log(description );
                        //console.log(storage );
                        //console.log(id );
                        //console.log(cpu );
                    }
                },
                'json');
            })(allsites[j]);
        }
    };

    function userHPCLoadJobTable() {
        var currentuser;
        $('#userHpcJobResultTable').dataTable().fnClearTable();
        currentuser = userid;
        for (var j = 0; j < allsites.length; j += 1) { (function(siteName) {
                $.post('/' + siteName + '/hpc/execute_wait/mpiapi.show_job_for_user.json', {
                    username: currentuser
                },
                function(serverResponse) {
                    var tid;
                    var tnc;
                    var inputfile;
                    var command;
                    var state;
                    var result;
                    var jobid;
                    var starttime;
                    var endtime;
                    var resultState;

                    for (var i = 0; i < serverResponse[0]; i += 1) {

                        tid = serverResponse[1][i].template_id;

                        tnc = serverResponse[1][i].template_node_cnt;

                        inputfile = serverResponse[1][i].inputfile;

                        command = serverResponse[1][i].command;

                        state = serverResponse[1][i].state;

                        result = serverResponse[1][i].result;

                        jobid = serverResponse[1][i].job_id;

                        starttime = serverResponse[1][i].start_time;

                        endtime = serverResponse[1][i].end_time;

                        if (result === '') {
                            resultState = 'disabled="true"';
                        }

                        else {
                            resultState = '';
                        }

                        $('#userHpcJobResultTable').dataTable().fnAddData([
                        siteName, jobid, tid, tnc, inputfile, command, state, starttime, endtime, '<input type="button" value="Download" onclick="window.open(\'/storage/download?path=' + result + '\')" ' + resultState + '  > </input> ' ]);

                        // console.log(serverResponse);
                        //console.log(tid );
                        //  console.log(tnc );
                        //  console.log(inputfile );
                        //  console.log(command );
                        //  console.log(state );
                        //  console.log(result );
                    }
                },
                'json');
            })(allsites[j]);
        }
    };

    function userHPCLoadVirtualVMInfos() {
        var currentuser;
        $('#userHpcVirtualClusterTable').dataTable().fnClearTable();
        currentuser = userid;
        for (var j = 0; j < allsites.length; j += 1) { (function(siteName) {

                //VM Cluster List Table
                $.post('/' + siteName + '/hpc/execute_wait/mpiapi.show_user_cluster.json', {
                    username: currentuser
                },
                function(serverResponse) {
                    var cid;
                    var iid;
                    var mcpu;
                    var mmem;
                    var scpu;
                    var smem;
                    var scount;
                    var status;
                    var stime;
                    var etime;
                    var ip;
                    var sshkey;
                    var sshkeystate;

                    for (var i = 0; i < serverResponse[0]; i += 1) {

                        cid = serverResponse[1][i].cluster_id;

                        iid = serverResponse[1][i].template_id;

                        status = serverResponse[1][i].state;

                        stime = serverResponse[1][i].start_time;

                        etime = serverResponse[1][i].end_time;

                        mcpu = serverResponse[1][i].master_vcpu;

                        mmem = serverResponse[1][i].master_memory;

                        scpu = serverResponse[1][i].slave_vcpu;

                        smem = serverResponse[1][i].slave_memory;

                        scount = serverResponse[1][i].slave_count;

                        ip = serverResponse[1][i].master_ipv6;

                        sshkey = serverResponse[1][i].master_key;

                        if (sshkey === '') {
                            sshkeystate = 'disabled="true"';
                        }

                        else {
                            sshkeystate = '';
                        }

                        $('#userHpcVirtualClusterTable').dataTable().fnAddData([
                        siteName, cid, iid, mcpu, mmem, scpu, smem, scount, status, stime, etime, ip, '<input type="button" value="Download" onclick="window.open(\'/storage/download?path=' + sshkey + '\')" ' + sshkeystate + '  > </input> ' ]);

                        //console.log(serverResponse);
                        //console.log(tid );
                        //  console.log(tnc );
                        //  console.log(inputfile );
                        //  console.log(command );
                        //  console.log(state );
                        //  console.log(result );
                    }
                },
                'json');

            })(allsites[j]);
        }
    };

    function userHPCLoadVirtualImageInfos() {
        var currentuser;
        $('#userHpcVirtualClusterTemplateTable').dataTable().fnClearTable();
        currentuser = userid;
        for (var j = 0; j < allsites.length; j += 1) { (function(siteName) {

                //VM Cluster List Table
                //Image Table
                $.post('/' + siteName + '/hpc/execute_wait/mpiapi.show_vm_cluster_template.json', {},
                function(serverResponse) {
                    var iid;
                    var disk;
                    var description;

                    for (var i = 0; i < serverResponse[0]; i += 1) {

                        iid = serverResponse[1][i].template_id;

                        disk = serverResponse[1][i].disk;

                        description = serverResponse[1][i].name;

                        hpcVMDescription[description] = serverResponse[1][i].description;

                        $('#userHpcVirtualClusterTemplateTable').dataTable().fnAddData([
                        siteName, iid, disk, ' <input type="button" value="' + description + '" onclick="hpcShowVMDescription()" style="width:120px"  > </input>' ]);

                        //console.log(serverResponse);
                        //console.log(tid );
                        //  console.log(tnc );
                        //  console.log(inputfile );
                        //  console.log(command );
                        //  console.log(state );
                        //  console.log(result );
                    }
                },
                'json');
            })(allsites[j]);
        }
    };

    userHPCLoadHPCTemplateTable();
    userHPCLoadJobTable();
    userHPCLoadVirtualVMInfos();
    userHPCLoadVirtualImageInfos();

    //////////////////////////////
    // uploader
    //////////////////////////////
    var ajaxUserLaunchJobFromCommandInputFileFieldForm = new qq.FileUploader({
        element: $('#ajaxUserLaunchJobFromCommandInputFileFieldForm')[0],
        multiple: true,
        onComplete: function(id, fileName, responseJSON) {
            if (responseJSON.success) {
                hpcJobInputFiles.addObject(responseJSON.filename);
            }
        },
        action: '/storage/upload_tmpfile'
    });
    // console.log($('#ajaxUserLaunchJobFromCommandInputFileFieldForm')[0]);
    var ajaxUserLaunchJobFromSourceSourceFileFieldForm = new qq.FileUploader({
        element: $('#ajaxUserLaunchJobFromSourceSourceFileFieldForm')[0],
        multiple: true,
        onComplete: function(id, fileName, responseJSON) {
            if (responseJSON.success) {
                hpcJobSourceFiles.addObject(responseJSON.filename);
            }
        },
        action: '/storage/upload_tmpfile'
    });
    // console.log($('#ajaxUserLaunchJobFromSourceSourceFileFieldForm')[0]);
    var ajaxUserLaunchJobFromSourceInputFileFieldForm = new qq.FileUploader({
        element: $('#ajaxUserLaunchJobFromSourceInputFileFieldForm')[0],
        multiple: true,
        onComplete: function(id, fileName, responseJSON) {
            if (responseJSON.success) {
                hpcJobInputFiles.addObject(responseJSON.filename);
            }
        },
        action: '/storage/upload_tmpfile'
    });
    // console.log($('#ajaxUserLaunchJobFromSourceInputFileFieldForm')[0]);
    $('#LaunchJobFromCommandButton').click(function(event) {
        var anSelected = fnGetSelected(userHpcTemplateInfoTable);
        var a = $('td', anSelected);
        if (a.length === 0) {
            alert("please select one row!");
            return 0;
        }

        var sitename = $(a[0]).text();
        var templateid = $(a[1]).text();
        var currentuser;
        var templatecnt = document.getElementById('userLaunchJobFromCommandAmountField').value;
        var command = document.getElementById('userLaunchJobFromCommandCommandField').value;
        var files = '';
        var inputShow, inputShows, inputShowLength;
        var ipnutFileCNT;

        ipnutFileCNT = hpcJobInputFiles.length;

        inputShows = '';

        for (var i = 0; i < ipnutFileCNT; i += 1) {
            files += hpcJobInputFiles[i];
            inputShow = hpcJobInputFiles[i].split("/");
            inputShowLength = inputShow.length;
            inputShows += inputShow[inputShowLength - 1];
            if (i < ipnutFileCNT - 1) {
                files += ',';
                inputShows += ',';
            }
        }
        $("#craneModalDialogContent").text("Note:Your request will be sent to site " + sitename + ".If you want to choose other sites,please click the [site] button on top right corner.Are you sure to submit this app job?Template_ID:" + templateid + ",Template_Number:" + templatecnt + ",Command:" + command + ",Input_Files:\"" + inputShows + "\"");
        $('#craneModalDialog').dialog({
            buttons: {
                Confirm: function() {
                    $(this).dialog('close');
                    //	$.post('/app/whoiam', {},
                    //	function(serverResponse) {
                    currentuser = userid; //serverResponse.userid;
                    $.post('/' + sitename + '/hpc/execute_wait/mpiapi.insert_app_job_into_queue.json', {
                        template_id: templateid,
                        template_node_cnt: templatecnt,
                        username: currentuser,
                        input: files,
                        app_command: command
                    },
                    function(serverResponse) {
                        if (serverResponse > 0) {
                            alert("Succeeded!");
                        }

                        else {

                            alert("Failed!");

                        }
                        hpcJobInputFiles = [];
                    },
                    'json');
                    //},
                    //'json');
                },

                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        }).dialog('open');
    });

    $('#LaunchJobFromSourceButton').click(function(event) {
        var anSelected = fnGetSelected(userHpcTemplateInfoTable);
        var a = $('td', anSelected);
        if (a.length === 0) {
            alert("please select one row!");
            return 0;
        }

        var sitename = $(a[0]).text();
        var templateid = $(a[1]).text();
        var currentuser;
        var templatecnt = document.getElementById('userLaunchJobFromSourceAmountField').value;
        var inputs = '';
        var sources = '';
        var ipnutFileCNT, sourceFileCNT;
        var inputShow, inputShows, inputShowLength;
        var sourceShow, sourceShows, sourceShowLength;

        ipnutFileCNT = hpcJobInputFiles.length;
        sourceFileCNT = hpcJobSourceFiles.length;

        inputShows = '';
        sourceShows = '';
		var i;

        for (i = 0; i < ipnutFileCNT; ++i) {
            inputs += hpcJobInputFiles[i];
            inputShow = hpcJobInputFiles[i].split("/");
            inputShowLength = inputShow.length;
            inputShows += inputShow[inputShowLength - 1];
            if (i < ipnutFileCNT - 1) {
                inputs += ',';
                inputShows += ',';
            }
        }

        for (i = 0; i < sourceFileCNT; ++i) {
            sources += hpcJobSourceFiles[i];
            sourceShow = hpcJobSourceFiles[i].split("/");
            sourceShowLength = sourceShow.length;
            sourceShows += sourceShow[sourceShowLength - 1];
            if (i < sourceFileCNT - 1) {
                sources += ',';
                sourceShows += ',';
            }
        }

        $("#craneModalDialogContent").text("Note:Your request will be sent to site " + sitename + ".If you want to choose other sites,please click the [site] button on top right corner.Are you sure to submit this source job?Template_ID:" + templateid + ",Template_Number:" + templatecnt + ",Input_Files:\"" + inputShows + "\",Source_Files:\"" + sourceShows + "\"");
        $('#craneModalDialog').dialog({
            buttons: {
                Confirm: function() {
                    $(this).dialog('close');
                    //$.post('/app/whoiam', {},
                    //function(serverResponse) {
                    currentuser = userid; //serverResponse.userid;
                    $.post('/' + sitename + '/hpc/execute_wait/mpiapi.insert_source_job_into_queue.json', {
                        template_id: templateid,
                        template_node_cnt: templatecnt,
                        username: currentuser,
                        source: sources,
                        input: inputs
                    },
                    function(serverResponse) {
                        if (serverResponse > 0) {
                            alert("Succeeded!");
                        }

                        else {

                            alert("Failed!");

                        }
                        hpcJobInputFiles = [];
                        hpcJobSourceFiles = [];
                    },
                    'json');
                    //	},
                    //	'json');
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        }).dialog('open');

    });

    $('#userHpcDeleteJobButton').click(function() {
        var anSelected = fnGetSelected(userHpcJobResultTable);
        var a = $('td', anSelected);
        if (a.length === 0) {
            alert("please select one row!");
            return 0;
        }

        var sitename = $(a[0]).text();
        var job = $(a[1]).text();

        $("#craneModalDialogContent").text("Are you sure to delete this job?Job_ID:" + job);
        $('#craneModalDialog').dialog({
            buttons: {
                Confirm: function() {
                    $(this).dialog('close');
                    $.post('/' + sitename + '/hpc/execute_wait/mpiapi.delete_job.json', {
                        jobid: job
                    },
                    function(serverResponse) {
                        if (serverResponse == null) {

                            alert("Delete failed!");
                            return 0;

                        }
                        else {
                            userHPCLoadJobTable();

                        }
                    },
                    'json');
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        }).dialog('open');

    });

    $('#userHpcLaunchJobInfoRefreshButton').click(function(event) {
        userHPCLoadHPCTemplateTable();
    });

    $('#userHpcJobRefreshButton').click(function(event) {
        userHPCLoadJobTable();
    });

    //////////////////////////////////////////////////////////
    ///////  Virtual Cluster
    //////////////////////////////////////////////////////////
    $('#userVirtualClusterCreateButton').click(function() {
        $('#userHpcVirtualClusterCreationDialog').dialog({
            width: 450,
            height: 500,
            autoOpen: false,
            modal: false,
            title: 'Create Virtual Cluster',
            buttons: {
                Confirm: function() {
                    $(this).dialog('close');
                    var anSelected = fnGetSelected(userHpcVirtualClusterTemplateTable);
                    var a = $('td', anSelected);
                    if (a.length === 0) {
                        alert("please select one row!");
                        return 0;
                    }

                    var sitename = $(a[0]).text();
                    var iid = $(a[1]).text();
                    var currentuser = userid;
                    var mcpu = document.getElementById('userHpcVirtualClusterCreationDialogMasterCPUCountField').value;
                    var mmem = document.getElementById('userHpcVirtualClusterCreationDialogMasterMemoryField').value;
                    var scpu = document.getElementById('userHpcVirtualClusterCreationDialogSlaveCPUCountField').value;
                    var smem = document.getElementById('userHpcVirtualClusterCreationDialogSlaveMemoryField').value;
                    var scount = document.getElementById('userHpcVirtualClusterCreationDialogSlaveCountField').value;

                    $.post('/' + sitename + '/hpc/execute_wait/mpiapi.insert_cluster_job.json', {
                        username: currentuser,
                        template_id: iid,
                        master_vcpu: mcpu,
                        master_memory: mmem,
                        slave_vcpu: scpu,
                        slave_memory: smem,
                        slave_count: scount
                    },
                    function(serverResponse) {
                        if (serverResponse == 1) {
                            alert("Creation successfully!");
                            userHPCLoadVirtualVMInfos();

                        }
                        else {
                            alert("Creation failed!");
                            return 0;

                        }
                    },
                    'json');
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        }).dialog('open');
    });

    $('#userVirtualClusterDeleteButton').click(function() {
        var anSelected = fnGetSelected(userHpcVirtualClusterTable);
        var a = $('td', anSelected);
        if (a.length === 0) {
            alert("please select one row!");
            return 0;
        }

        var sitename = $(a[0]).text();
        var cid = $(a[1]).text();
        var currentuser = userid;
        $("#craneModalDialogContent").text("Note:Your request will be sent to site " + sitename + ".If you want to choose other sites,please click the [site] button on top right corner.Are you sure to delete this cluster?Cluster_ID:" + cid);
        $('#craneModalDialog').dialog({
            buttons: {
                Confirm: function() {
                    $(this).dialog('close');
                    //$.post('/app/whoiam', {},
                    //function(serverResponse) {
                    $.post('/' + sitename + '/hpc/execute_wait/mpiapi.delete_cluster.json', {
                        username: currentuser,
                        cluster_id: cid
                    },
                    function(serverResponse) {
                        if (serverResponse == 1) {
                            userHPCLoadVirtualVMInfos();
                            alert("Delete successfully!");

                        }
                        else {

                            alert("Delete failed!");
                            return 0;
                        }
                    },
                    'json');
                },
                Cancel: function() {
                    $(this).dialog('close');
                }
            }
        }).dialog('open');

    });

    $('#userHpcVirtualClusterRefreshButton').click(function() {
        userHPCLoadVirtualVMInfos();
    });

};
